<template>
  <div>
    <my-breadcrumb :items="['系统设置', '价格体系']"></my-breadcrumb>
    <Button type="primary" @click="addSetup">添加体系</Button>
    <div style="margin-top: 16px;">
      <Table :columns="columns" :data="tableData" stripe></Table>
    </div>
    <Modal v-model="showAdd" width="650" @on-ok="subSetup" @on-cancel="cancel" :mask-closable="false" :closable="false" :loading="loading">
      <div slot="header">
        <p v-show="isAdd">
          添加价格体系
          <span style="color:#ed3f14;">（温馨提示：添加之后不能删除，将永久存在，请谨慎考虑之后添加）</span>
        </p>
        <p v-show="isUpdate">更新价格体系</p>
      </div>
      <Form :model="addData" :label-width="70" ref="form" :rules="formRules">
        <FormItem label="体系名称" style="width: 80%;" prop="name">
          <Input v-model="addData.name" />
        </FormItem>
        <FormItem label="体系描述" style="width: 80%;" prop="description">
          <Input v-model="addData.description" />
        </FormItem>
        <Row>
          <i-col span="8">
            <FormItem label="折扣比例" style="width: 80%;" prop="branchDiscount">
              <InputNumber v-model="addData.branchDiscount"/>%
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="期望利润" style="width: 80%;" :label-width="60" prop="expectedProfit">
              <InputNumber v-model="addData.expectedProfit"/>
              <span>%</span>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="最低利润" style="width: 80%;" :label-width="60" prop="minProfit">
              <InputNumber v-model="addData.minProfit"/>
              <span>%</span>
            </FormItem>
          </i-col>
        </Row>
        <FormItem label="是否启用还价" :label-width="90" prop="isSupportMinProfit">
          <i-switch v-model="addData.isSupportMinProfit" :true-value="1" :false-value="0">
            <span slot="open">开</span>
            <span slot="close">关</span>
          </i-switch>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="showAddPrice" @on-ok="sureAddSetup">
      <Table :data="goods" :columns="goodsCol"></Table>
    </Modal>
  </div>
</template>

<script>
export default {
  name: 'customer',
  data () {
    return {
      url: {
        setupsUrl: '/discount/setup/manage/select/all/branch/customer',
        addSetup: '/discount/setup/manage/add/branch/customer/setup',
        updateSetup: '/discount/setup/manage/update/branch/customer/setup',
        list: '/goods/manage/get/goods/sku/no/set/price'
      },
      showAdd: false,
      isAdd: false,
      isUpdate: false,
      updateId: '',
      addData: {
        name: '',
        description: '',
        branchDiscount: null,
        expectedProfit: null,
        minProfit: null,
        isSupportMinProfit: 0
      },
      switchBtn: false,
      oldValue: {},
      columns: [
        {
          title: '体系名称',
          key: 'name'
        },
        {
          title: '体系描述',
          key: 'description',
          width: 400
        },
        {
          title: '折扣比例',
          key: 'branchDiscount',
          width: 100,
          render: (h, params) => {
            return h('span', {
              style: {
                fontWeight: '800',
                color: '#19be6b'
              }
            }, params.row.branchDiscount + '%')
          }
        },
        {
          title: '期望利润',
          key: 'expectedProfit',
          render: (h, params) => {
            let str = ''
            if (params.row.expectedProfit) {
              str = params.row.expectedProfit + '%'
            }
            return h('span', {
              style: {
                color: '#19be6b',
                fontWeight: '800'
              }
            }, str)
          }
        },
        {
          title: '最低利润',
          key: 'minProfit',
          render: (h, params) => {
            return h('span', {
              style: {
                color: '#ed3f14',
                fontWeight: '800'
              }
            }, params.row.minProfit ? params.row.minProfit + '%' : '')
          }
        },
        {
          title: '还价',
          key: 'isSupportMinProfit',
          width: 100,
          render: (h, params) => {
            let _self = this
            return h('i-switch', {
              props: {
                trueValue: 1,
                falseValue: 0,
                value: params.row.isSupportMinProfit,
                disabled: _self.switchBtn
              },
              on: {
                input: (e) => {
                  params.row.isSupportMinProfit = e
                },
                'on-change': (val) => {
                  _self.switchBtn = true
                  _self.openDicker(val, params.row)
                }
              }
            }, [
              h('span', {
                slot: 'open'
              }, '开'),
              h('span', {
                slot: 'close'
              }, '关')
            ])
          }
        },
        {
          title: '操作',
          key: 'status',
          align: 'center',
          render: (h, params) => {
            let _self = this
            return h('Button', {
              props: {
                type: 'primary',
                size: 'small'
              },
              style: {
                marginLeft: '8px'
              },
              on: {
                click: () => {
                  _self.updateId = params.row.id
                  for (let i in _self.addData) {
                    _self.addData[i] = params.row[i]
                  }
                  _self.oldValue = JSON.parse(JSON.stringify(_self.addData))
                  _self.isUpdate = true
                  _self.showAdd = true
                }
              }
            }, '修改')
          }
        }
      ],
      tableData: [],
      showAddPrice: false,
      goods: [],
      goodsCol: [
        {
          type: 'index',
          width: 50
        },
        {
          title: '商品sku名称',
          key: 'goodsSkuName'
        },
        {
          title: '成本价',
          key: 'costPrice',
          render: (h, params) => {
            return h('span', params.row.costPrice / 100 + '￥')
          }
        },
        {
          title: '体系价格',
          render: (h, params) => {
            return h('InputNumber', {
              props: {
                min: 0.01,
                value: null
              },
              on: {
                input: (e) => {
                  this.prices[params.index] = e
                }
              }
            })
          }
        }
      ],
      prices: [],
      loading: true,
      formRules: {
        name: [
          { required: true, message: '体系名称不能为空', trigger: 'blur' }
        ],
        branchDiscount: [
          { required: true, message: '折扣比例不能为空', trigger: 'blur', type: 'number' }
        ]
      }
    }
  },
  methods: {
    addSetup () {
      this.isAdd = true
      this.showAdd = true
      this.$refs.form.resetFields()
    },
    cancel () {
      this.isAdd = false
      this.isUpdate = false
    },
    sureAddSetup () {
      this.$Modal.confirm({
        title: '请确认添加',
        content: '<p>你确定你想好要添加该体系吗，确认添加之后不可以删除的哦</p>',
        loading: true,
        onOk: () => {
          this.subPrice()
        },
        onCancel: () => {
          this.cancel()
        }
      })
    },
    subSetup () {
      if (this.isAdd) {
        this.subAddSetup()
      }
      if (this.isUpdate) {
        if (JSON.stringify(this.addData) !== JSON.stringify(this.oldValue)) {
          this.subUpdateSetup()
          this.isUpdate = false
        }
      }
    },
    subAddSetup () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$ajax.post(this.url.list).then(res => {
            if (res.data.success) {
              if (res.data.data[0]) {
                this.goods = res.data.data
                this.showAddPrice = true
              } else {
                this.sureAddSetup()
              }
            }
          })
        } else {
          this.$Message.error('信息填写错误')
        }
      })
    },
    subPrice () {
      this.isAdd = false
      let goodsPriceSetup = []
      let isOK = true
      this.prices.forEach((item, index) => {
        if (item === null) {
          isOK = false
          return
        }
        goodsPriceSetup.push({
          goodsSkuId: this.goods[index].skuId,
          price: item * 100
        })
      })
      if (!isOK) {
        return
      }
      let branchCustomerSetup = {
        ...(this.addData)
      }
      let params = {
        goodsPriceSetup,
        branchCustomerSetup
      }
      this.$ajax.post(this.url.addSetup, params)
        .then(res => {
          if (res.data.success) {
            this.initSetupData()
            this.$Message.success('添加成功')
            this.$Modal.remove()
          }
        })
    },
    subUpdateSetup () {
      let params = {
        ...(this.addData),
        id: this.updateId
      }
      this.$ajax.post(this.url.updateSetup, JSON.stringify(params)).then(res => {
        if (res.data.success) {
          this.initSetupData()
          this.showAdd = false
          this.$Message.success('更新成功')
        }
      })
    },
    openDicker (val, data) {
      let params = {}
      for (let i in this.addData) {
        params[i] = data[i]
      }
      params.id = data.id
      params.isSupportMinProfit = val
      this.$ajax.post(this.url.updateSetup, JSON.stringify(params)).then(res => {
        if (res.data.success) {
          this.$Message.success('更新成功')
        }
        this.switchBtn = false
      })
    },
    initSetupData () {
      this.$ajax.get(this.url.setupsUrl).then((res) => {
        this.tableData = res.data.data
      })
    }
  },
  created () {
    this.initSetupData()
  }
}
</script>

<style scoped>

</style>
